const { Menu, dialog } = require('electron')
const got = require('got').default
const path = require('path')
const imageType = require('image-type')
const randomstring = require('randomstring')
const fs = require('fs')

const saveAs = async (srcUrl) => {
    // console.log(srcUrl, 'srcUrl');avif 不支持。
    if (srcUrl) {
        const contextMenu = Menu.buildFromTemplate([
            {
                label: '图片另存为...',
                click: () => {
                    // 1、获取url地址
                    // 2、将图片地址变为2进制  通过imageType 获取文件类型
                    // 3、调用 dialog 将文件存到指定文件路径位置
                    got.get(srcUrl).then(async (res) => {
                        const chunk = Buffer.from(res.rawBody)
                        const { ext } = imageType(chunk) // { ext: 'png', mime: 'image/png' }
                        const { canceled, filePath } = await dialog.showSaveDialog({ // 返回一个promise 对象
                            // canceled: false,
                            // filePath:'D:\\LearnProject\\studyPROJECT\\readIt\\public\\uploads\\dL6Knc7haP.png'
                            // 所以要用async 和 await 来处理结果... 不然一直是pending状态
                            title: '图片另存为...',
                            defaultPath: path.resolve(__dirname, '../public/uploads/' + randomstring.generate(10) + '.' + ext)
                        })
                        if (!canceled) { // 如果没有被取消... 将同步写入..文件存入指定目录
                            fs.writeFileSync(filePath, chunk)
                        }
                    }).catch(() => { })



                    //   got.get(srcUrl).then(async (response) => {
                    //     const chunk = Buffer.from(response.rawBody)

                    //     const imgType = imageType(chunk)

                    //     const { filePath, canceled } = await dialog.showSaveDialog({
                    //       title: '图片另存为',
                    //       defaultPath: path.resolve(__dirname, '../public/uploads/' + randomstring.generate(10) + '.' + imgType.ext)
                    //     })
                    //     if (!canceled) {
                    //       fs.writeFileSync(filePath, chunk)
                    //     }
                    //   }).catch((e)=>{})
                },
                accelerator: 'CommandOrControl+S'
            }
        ])

        contextMenu.popup()
    }
}

module.exports = saveAs